package cn.tedu.boot21.controller;

import cn.tedu.boot21.entity.User;
import cn.tedu.boot21.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody
    private String reg(User user){
        if(user.getUsername().trim().isEmpty()||user.getPassword().trim().isEmpty()||user.getNick().isEmpty()){
            return "输入信息错误!";
        }
        try (Connection conn = DBUtils.getConn();) {
            String sql = "select id from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                return "用户已存在!";
            }
            String s = "insert into user(username,password,nick) values(?,?,?)";
            PreparedStatement insertPs = conn.prepareStatement(s);
            insertPs.setString(1, user.getUsername());
            insertPs.setString(2, user.getPassword());
            insertPs.setString(3, user.getNick());
            insertPs.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "恭喜你,注册成功!";
    }

    @RequestMapping("/login")
    @ResponseBody
    private String login(User user){
        //soutp
        System.out.println("user = " + user);
        try (Connection conn = DBUtils.getConn();) {
            String sql = "select password from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                if((rs.getString(1)).equals(user.getPassword())){
                    return "登录成功!";
                }
                return "密码错误!";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "账号不存在!";
    }
}


